import {changeToArr, request, requestGBK, sleep} from './utils'
import * as R from 'ramda'
const cheerio = require('cheerio')
const qs = require('querystring')
const path = window.node_path
const fs = window.fileSys
const datas = window.datas
export const filename = path.resolve(window.current_dir, 'activities.json')

export async function addActivity(url, log) {
  let title
  let actId
  if (/^http(s?):/.test(url)) {
    const res = await requestGBK({
      url
    })
    const ma = res.match(/ossweb-img.qq.com\/images\/ams\/atm\/reporting.js\?action=\d+/)
    const $ = cheerio.load(res)
    title = $('title').text().split('-')[0]
    if (ma) {
      const index = ma[0].indexOf('=')
      if (index !== 0) {
        actId = ma[0].substr(index + 1)
      } else {
        if (typeof log === 'function') log({content: '网页解析失败：正则无法匹配活动id'}, {style: {color: 'red'}})
      }
    } else {
      if (typeof log === 'function') log({content: '网页解析失败：正则无匹配结果'}, {style: {color: 'red'}})
    }
  } else {
    actId = url.split('-')[0]
    title = url.split('-')[1]
  }
  const actInfo = await request({
    url: `http://bns.qq.com/comm-htdocs/js/ams/actDesc/${actId.substr(-3)}/${actId}/act.desc.js`
  })
  // eslint-disable-next-line
  const f = new Function(`${actInfo};return ams_actdesc`)
  const ams_actdesc = f()
  const data = {
    ...ams_actdesc,
    checked: true,
    title,
    iFlowIds: R.compose(
      arr => {
        let ids = []
        R.forEachObjIndexed((item, key) => {
          ids.push(key.substr(2))
        })(arr)
        return ids
      }
    )(ams_actdesc.flows)
  }
  delete data.flows
  let avtivities = []
  try {
    avtivities = JSON.parse(fs.readFileSync(filename))
  } catch (err) {}
  avtivities = changeToArr(avtivities)
  avtivities.unshift(data)
  avtivities = R.dropRepeatsWith((a, b) => a.iActivityId === b.iActivityId)(avtivities)
  fs.writeFileSync(filename, JSON.stringify(avtivities), 'utf8')
  log({
    content: `活动添加成功-${data.title}`
  })
  return avtivities
}

export function getActivities() {
  let avtivities = []
  try {
    avtivities = JSON.parse(fs.readFileSync(filename))
  } catch (err) {
    console.log(err)
  }
  return avtivities
}

export function updateActivities(avtivities) {
  fs.writeFileSync(filename, JSON.stringify(avtivities), 'utf8')
}

export const gift = {
  log() {},
  userInfo: {},
  activities: [],
  isStop: true,
  async start() {
    for (let i = 0; i < this.activities.length; i++) {
      if (this.isStop) return
      if (this.activities[i].checked) {
        const p = this.activities[i]
        const bindData = {
          sServiceType: p.sServiceType,
          user_area: this.userInfo.area,
          user_roleId: this.userInfo.role,
          user_md5str: this.userInfo.md5str,
          iActivityId: p.iActivityId,
          iFlowId: p.iAreaRoleFlowId,
          g_tk: datas.g_tk,
          user_checkparam: this.userInfo.checkparam,
          xhr: 1,
          sServiceDepartment: p.sServiceDepartment
        }
        const bindRes = await request({
          method: 'post',
          url: `https://${p.sAmePcUrl}?${qs.stringify(bindData)}`,
          data: bindData
        })
        this.log({content: `${p.title}：${(bindRes.flowRet && bindRes.flowRet.sMsg) || bindRes.msg}`})
        for (let k = 0; k < this.activities[i].iFlowIds.length; k++) {
          if (this.isStop) return
          await sleep()
          const item = this.activities[i].iFlowIds[k]
          const resData = {
            iActivityId: p.iActivityId,
            iFlowId: item,
            g_tk: datas.g_tk,
            e_code: 0,
            g_code: 0,
            xhr: 1,
            checkparam: this.userInfo.checkparam,
            sServiceDepartment: p.sServiceDepartment,
            sServiceType: p.sServiceType
          }
          const res = await request({
            method: 'post',
            url: `https://${p.sAmePcUrl}?${qs.stringify(resData)}`,
            data: resData
          })
          this.log({content: `${p.title}-${k + 1}：${(res.flowRet && res.flowRet.sMsg) || res.msg}`})
        }
      }
    }
  }
}
